package com.shine.sys.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.shine.common.repository.hibernate.HibernateDao;
import com.shine.common.utils.BeanUtils;
import com.shine.common.utils.security.Md5Utils;
import com.shine.common.web.model.DataGrid;
import com.shine.common.web.model.DataTables;
import com.shine.common.web.model.Page;
import com.shine.common.web.model.SystemContext;
import com.shine.sys.entity.User;
import com.shine.sys.service.UserService;
import com.shine.sys.web.dto.UserDto;

@Service
public class UserServiceImpl extends HibernateDao<User, Integer> implements UserService {
	
	@Override
	public void add(UserDto dto) {
		User entity = new User() ;
		BeanUtils.copyNotNullProperties(dto, entity);
		entity.randomSalt();
		entity.setPassword(encryptPassword(entity.getUsername(), entity.getPassword(), entity.getSalt()));
		super.save(entity); 
	}

	private String encryptPassword(String username, String password, String salt) {
		return Md5Utils.hash(username + password + salt);
	}
	
	@Override
	public void delete(boolean type, String ids) {
		if(null != ids && ids.length() > 0) {
			String[] split = ids.split(",") ;
			Map<String, Object> alias = new HashMap<String, Object>() ;
			alias.put("ids", split) ;
			if(type) {
				super.executeSQL("update sys_user t set t.deleted=1 where id in(:ids)", alias) ;
			} else {
				//恢复已删除的用户
				super.executeSQL("update sys_user t set t.deleted=0 where id in(:ids)", alias) ;
			}
		}
	}

	@Override
	public void deleteForPhysical(String ids) {
		if(null != ids && ids.length() > 0) {
			String[] split = ids.split(",") ;
			for (String id : split) {
				super.deleteById(Integer.parseInt(id));
			}
		}
	}

	@Override
	public void update(UserDto dto) {
		User entity = new User() ;
		BeanUtils.copyNotNullProperties(dto, entity);
		super.update(entity);
	}

	@Override
	public UserDto get(Integer id) {
		User entity = super.getEntity(id);
		UserDto dto = new UserDto() ;
		BeanUtils.copyNotNullProperties(entity, dto);
		return dto;
	}
	
	@Override
	public DataGrid datagrid(UserDto dto) {
		
		DataGrid dg = new DataGrid() ;
		
		Page<UserDto> findByPage = this.findByPage(dto) ;
		dg.setTotal(((Integer)findByPage.getTotalNumber()).longValue());
		dg.setRows(findByPage.getDataRows()) ;
		
		return dg;
	}
	

	@Override
	public DataTables datatables(UserDto dto) {
		Page<UserDto> findByPage = this.findByPage(dto) ;
		
		return new DataTables(SystemContext.getDraw(), findByPage.getTotalNumber(), findByPage.getTotalNumber(), findByPage.getDataRows(), SystemContext.getPageNumber(), SystemContext.getCurrentPage()) ;
	}
	
	@Override
	public Page<UserDto> findByPage(UserDto dto) {
		StringBuffer queryString = new StringBuffer("SELECT t.* FROM sys_user t WHERE 1=1") ;
		
		Map<String, Object> alias = new HashMap<String, Object>() ;
		queryString = addWhere(queryString, alias, dto) ;
		
		return super.findPageSQL(queryString.toString(), alias, User.class, false) ;
	}
	
	private StringBuffer addWhere(StringBuffer queryString, Map<String, Object> alias, User entity) {
		if(null != entity) {
			if(null != entity.getId()) {
				queryString.append(" AND t.id=:id") ;
				alias.put("id", entity.getId()) ;
			}
			
			if(null != entity.getDeleted()) {
				if(null != entity.getDeleted() && !entity.getDeleted()) {
					queryString.append(" AND t.deleted=0") ;
				} else if(null != entity.getDeleted() && entity.getDeleted()) {
					queryString.append(" AND t.deleted=1") ;
				}
			}
			
			if(null != entity.getUsername() && !"".equals(entity.getUsername())) {
				queryString.append(" AND t.username like :email") ;
				alias.put("username", "%%" + entity.getUsername() + "%%") ;
			}
			if(null != entity.getStatus() && !"".equals(entity.getStatus())) {
				queryString.append(" AND t.status=:status") ;
				alias.put("status", entity.getStatus()) ;
			}
			if (entity.getStartTime() != null && !"".equals(entity.getStartTime())) {
				queryString.append(" AND date_format(t.createTime,'%Y-%m-%d')>= date_format(:startTime,'%Y-%m-%d')") ;
				alias.put("startTime", entity.getStartTime()) ;
			}
			if (entity.getEndTime() != null && !"".equals(entity.getEndTime())) {
				queryString.append(" AND date_format(t.createTime,'%Y-%m-%d')<= date_format(:endTime,'%Y-%m-%d')") ;
				alias.put("endTime", entity.getEndTime()) ;
			}
			if(entity.getQuickSearch() != null && !"".equals(entity.getQuickSearch())){
				queryString.append(" and ")
				.append("(")
				.append("t.username like '%%" + entity.getQuickSearch() + "%%'")
				.append(" or t.email like '%%" + entity.getQuickSearch() + "%%'")
				.append(" or t.mobile_phone_number like '%%" + entity.getQuickSearch() + "%%'")
				.append(")");
			}
		}
		return queryString;
	}
	

}
